import { useEffect, useState } from 'react';

import { fetchVulnerability } from '../../../../actions/vulnerability-actions';
import Tabs, { type TabsEntry } from '../../../../components/common/tabs/Tabs';
import useTabs from '../../../../components/common/tabs/useTabs';
import { useFormatter } from '../../../../components/i18n';
import { type VulnerabilityOutput, type VulnerabilitySimple } from '../../../../utils/api-types';
import useEnterpriseEdition from '../../../../utils/hooks/useEnterpriseEdition';
import GeneralVulnerabilityInfoTab from './GeneralVulnerabilityInfoTab';
import RemediationInfoTab from './RemediationInfoTab';
import TabLabelWithEE from './TabLabelWithEE';
import VulnerabilityTabPanel from './VulnerabilityTabPanel';

interface Props { selectedVulnerability: VulnerabilitySimple }

export type VulnerabilityStatus = 'loading' | 'loaded' | 'notAvailable';

const VulnerabilityDetail = ({ selectedVulnerability }: Props) => {
  const { t } = useFormatter();

  const {
    isValidated: isEE,
    openDialog: openEEDialog,
    setEEFeatureDetectedInfo,
  } = useEnterpriseEdition();

  const [vulnerability, setCve] = useState<VulnerabilityOutput | null>(null);
  const [vulnerabilityStatus, setVulnerabilityStatus] = useState<VulnerabilityStatus>('loading');

  useEffect(() => {
    if (!selectedVulnerability.vulnerability_id) return;

    setVulnerabilityStatus('loading');

    fetchVulnerability(selectedVulnerability.vulnerability_id)
      .then((res) => {
        setCve(res.data);
        setVulnerabilityStatus(res.data ? 'loaded' : 'notAvailable');
      })
      .catch(() => setVulnerabilityStatus('notAvailable'));
  }, [selectedVulnerability]);

  const tabEntries: TabsEntry[] = [{
    key: 'General',
    label: t('General'),
  }, {
    key: 'Remediation',
    label: <TabLabelWithEE label={t('Remediation')} />,
  }];
  const { currentTab, handleChangeTab } = useTabs(tabEntries[0].key);

  const renderTabPanels = () => {
    switch (currentTab) {
      case 'General':
        return (
          <VulnerabilityTabPanel status={vulnerabilityStatus} vulnerability={vulnerability}>
            <GeneralVulnerabilityInfoTab vulnerability={vulnerability!} />
          </VulnerabilityTabPanel>
        );
      case 'Remediation':
        return (
          <VulnerabilityTabPanel status={vulnerabilityStatus} vulnerability={vulnerability}>
            <RemediationInfoTab vulnerability={vulnerability!} />
          </VulnerabilityTabPanel>
        );
      default:
        return null;
    }
  };

  useEffect(() => {
    if (currentTab === 'Remediation' && !isEE) {
      handleChangeTab('General');
      setEEFeatureDetectedInfo(t('Remediation'));
      openEEDialog();
    }
  }, [currentTab, isEE]);

  return (
    <>
      <Tabs
        entries={tabEntries}
        currentTab={currentTab}
        onChange={newValue => handleChangeTab(newValue)}
      />
      {renderTabPanels()}
    </>
  );
};

export default VulnerabilityDetail;
